﻿using System;
using System.Windows;
using System.Windows.Controls;
using DevExpress.AgDataGrid;
using DevExpress.AgDataGrid.Data;
using System.Windows.Documents;

namespace Test.Silverlight.DataGrid {
	public partial class PreviewLayout : UserControl {
		public PreviewLayout() {
			InitializeComponent();
			grid.DataSource = EmployeesData.DataSource;
			grid.Loaded += new RoutedEventHandler(grid_Loaded);
		}

		void grid_Loaded(object sender, RoutedEventArgs e) {
			grid.ApplyTemplate();
		}
        void grid_FocusedRowChanged(object sender, DevExpress.AgDataGrid.Data.FocusedRowChangedEventArgs e) {
            OnFocusedRowChanged(e.NewDataRow);
        }
        protected void OnFocusedRowChanged(object focusedRow) {
            if(PreviewContent.Content == null) PreviewContent.Content = grid.PreviewTemplate.LoadContent();
            PreviewContent.Height = double.NaN;
            PreviewContent.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            PreviewContent.Height = Math.Round(PreviewContent.DesiredSize.Height);
            PreviewContent.DataContext = focusedRow;
        }
        void grid_NewDataRow(object sender, NewDataRowEventArgs e) {
			if(RBToolTip == null || RBToolTip.IsChecked == false) return;
			AgPreviewToolTip tt = new AgPreviewToolTip();
			tt.DataContext = e.DataRow;
			tt.Content = grid.PreviewTemplate.LoadContent();
			ToolTipService.SetToolTip(e.Row, tt);
		}
        #region OptionsPanel
        string currentChecked;
        void rb_Checked(object sender, RoutedEventArgs e) {
            RadioButton rb = (RadioButton)sender;
            if (currentChecked == rb.Name) return;
            currentChecked = rb.Name;
            grid.BeginUpdate();
            try {
                if (sender == RBNormal) {
                    LayoutRoot.RowDefinitions[0].MaxHeight = 592;
                    grid.PreviewVisibility = DataPreviewVisibility.ForFocusedRow;
                    PreviewContent.Visibility = Visibility.Collapsed;
                }
                if (sender == RBToolTip) {
                    grid.PreviewVisibility = DataPreviewVisibility.Collapsed;
                    PreviewContent.Visibility = Visibility.Collapsed;
                    LayoutRoot.RowDefinitions[0].MaxHeight = 307;
                }
                if (sender == RBOutside) {
                    grid.PreviewVisibility = DataPreviewVisibility.Collapsed;
                    PreviewContent.Visibility = Visibility.Visible;
                    OnFocusedRowChanged(grid.FocusedDataRow);
                    LayoutRoot.RowDefinitions[0].MaxHeight = 307;
                }
                grid.TopRow = 0;
            } finally {
                grid.EndUpdate();
            }
        }
        #endregion
    }
}
